package rpg.data;

import java.io.File;
import java.util.List;

import org.jdom.Element;

import pedrosm.data.ScriptData;
import pedrosm.utils.Debug;

import square.data.DataGroup;
import square.data.ItemData;
import square.data.SpriteData;
import square.script.ItemScript;

/**
 * 
 * @author Pedro Silva Moreira
 */
public class ItemXML implements LoaderXML {
	private static ItemXML singleton = new ItemXML();
	
	// Creation
	private ItemXML() {
	}
	
	// Instance
	public static ItemXML instance() {
		return singleton;
	}
	
	// Load
	@SuppressWarnings("unchecked")
	public void load(String group, String name, Element origin) {
		Element elem = XML.loadXML(XML.DATA_FOLDER + "items" + File.separator
				+ group + File.separator + name + ".xml");

		ItemData data = new ItemData();
		// Group
		data.setGroup(group);
		
		// Name
		data.setName(elem.getAttributeValue("name"));

		// Type
		String type = elem.getAttributeValue("type");
		if (type != null)
			data.setType(type);

		// Script
		String script = elem.getAttributeValue("script");
		if(script != null) {
			data.setScript((ScriptData<ItemScript>) DataGroup.findScript(script));
		}
		
		// Sprite
		SpriteData sprite = DataGroup.findSprite(elem.getAttributeValue("sprite"));
		if (sprite == null) {
			Debug.debug("ItemXML", "Failed to create ItemData with sprite: "
					+ elem.getAttributeValue("sprite"));
			return;
		}
		data.setSprite(sprite);
		
		// Data
		parseData(elem, data);

		// Add
		DataGroup.getItems().add(data);
	}

	@SuppressWarnings("unchecked")
	public static void parseData(Element elem, ItemData data) {
		List<Element> attributes = elem.getChildren("attr");
		for (Element attr : attributes) {
			String name = attr.getAttributeValue("name");
			String value = attr.getAttributeValue("value");

			if (name.equals("walkAble")) {
				data.setWalkAble(Boolean.valueOf(value));
			} else if (name.equals("stack")) {
				data.setStack(Integer.valueOf(value));
			}
		}
	}
}
